package com.yystar.support.handler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.yystar.support.interfaceaccess.InterfaceAccessService;


@Component("securityHandler")
public class SecurityHandler implements LogicalHandler<LogicalMessageContext> {
	private static Log log = LogFactory.getLog(SecurityHandler.class);

	@Resource
	private InterfaceAccessService interfaceAccessService;

	@Override
	public void close(MessageContext context) {
		// nothing to clean up
	}

	@Override
	public boolean handleFault(LogicalMessageContext context) {
		return true;
	}

	@Override
	public boolean handleMessage(LogicalMessageContext context) {
		String ipAddr = ((HttpServletRequest) context.get(MessageContext.SERVLET_REQUEST)).getRemoteAddr();
		String serverAddr = ((HttpServletRequest) context.get(MessageContext.SERVLET_REQUEST)).getLocalAddr();
		if (ipAddr.contains("10.1.41") || "127.0.0.1".equals(ipAddr) || serverAddr.equals(ipAddr)) {
			return true;
		} else if (!interfaceAccessService.canAccess(ipAddr)) {
			log.warn("failed, forbidden ip address " + ipAddr);
			throw new RuntimeException("Failed, forbidden ip address.");
		}
		return true;
	}
}
